package com.example.libary.controller;

import com.example.libary.common.Result;
import com.example.libary.dto.LoginRequest;
import com.example.libary.dto.LoginResponse;
import com.example.libary.dto.RegisterRequest;
import com.example.libary.entity.User;
import com.example.libary.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 认证控制器
 */
@Tag(name = "认证管理", description = "登录、注册相关接口")
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final UserService userService;

    /**
     * 用户登录
     */
    @Operation(summary = "用户登录", description = "用户名密码登录")
    @PostMapping("/login")
    public Result<LoginResponse> login(@Parameter(description = "登录信息") @RequestBody @Valid LoginRequest loginRequest) {
        String token = userService.login(loginRequest.getUsername(), loginRequest.getPassword());
        
        User user = userService.getByUsername(loginRequest.getUsername());
        user.setPassword(null); // 不返回密码
        
        LoginResponse response = LoginResponse.builder()
                .token(token)
                .user(user)
                .build();
        
        return Result.success(response);
    }

    /**
     * 用户注册
     */
    @Operation(summary = "用户注册", description = "注册新用户")
    @PostMapping("/register")
    public Result<Void> register(@Parameter(description = "用户信息") @RequestBody @Valid RegisterRequest registerRequest) {
        User user = new User();
        BeanUtils.copyProperties(registerRequest, user);
        boolean success = userService.register(user);
        return success ? Result.success() : Result.error("注册失败");
    }
} 